<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  example all rights reserved.
 */
namespace app\http\middleware;

use think\facade\Config;

/**
 * 请求中间件-- 处理请求日志, cors处理.
 */
class RequestLog
{
    public function handle($request, \Closure $next)
    {
        //定义请求的请求头属性
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Origin, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
        header('Access-Control-Max-Age: 3600');

        $header = $request->header();
        //同源验证限制属性
        $auth_status = config('cors.auth_status');
        //针对框架处理请求部分本地请求无法获取Origin的特殊情况--识别为本地开发
        if (!isset($header['origin'])) {
            //开放调式 -- 默认前端为8080测试代理端口
            if ('DEVELOP' == $auth_status) {
                header('Access-Control-Allow-Origin: http://localhost:8080');
            }
        } else {
            
            $origin = $header['origin'];
            
            
            //应用接口访问登录模式状态[DEVELOP]状态下允许全部跨域,并区分不同环境的访问以保障[PRODUCT]环境接口的正常访问
            if ('DEVELOP' == $auth_status) {
                if ('localhost' == parse_url($origin, PHP_URL_HOST) || '127.0.0.1' == parse_url($origin, PHP_URL_HOST) || null == $origin || false !== strpos($origin, 'chrome-extension')) {
                    //全匹配跨域允许请求头设置
                    header('Access-Control-Allow-Origin: ' . $origin);
                } else {
                    //全匹配跨域允许请求头设置
                    header('Access-Control-Allow-Origin: ' . $origin);
                    //非本地调试开启产品模式的验证
                    $auth_status = 'PRODUCT';
                }
            }

            //应用接口访问登录模式状态[PRODUCT]状态下只允许白名单来源跨域访问
            if ('PRODUCT' == $auth_status) {
                //只针对白名单中的源进行跨域适配
                if (in_array(parse_url($origin, PHP_URL_HOST), config('cors.auth_white_list'))) {
                    header('Access-Control-Allow-Origin: ' . $origin);
                } else {
                    json(['status' => false, 'message' => 'PRODUCT模式: 禁止非法访问'])->send();
                    exit();
                }
            }
        }

        //如果是前端PUT类型的预请求--拦截并直接返回true
        if ('OPTIONS' == $request->method()) {
            json(true)->send();
            exit();
        }

        return $next($request);
    }
}
